package com.link.play.fit.ai.ui.view

import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.animation.LinearInterpolator
import androidx.appcompat.widget.AppCompatImageView

class RotateImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    // 控制旋转的动画对象
    private var rotateAnimator: ObjectAnimator? = null
    private var isRotating = false  // 动画状态标记

    // 启动旋转动画
    fun startRotate(duration: Long = 2000) {
        if (isRotating) return  // 避免重复启动

        rotateAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f).apply {
            this.duration = duration
            interpolator = LinearInterpolator()  // 匀速旋转
            repeatCount = ObjectAnimator.INFINITE  // 无限循环
            start()
        }
        isRotating = true
    }

    // 停止旋转动画并重置角度
    fun stopRotate(resetToZero: Boolean = true) {
        rotateAnimator?.cancel()
        rotateAnimator = null
        isRotating = false

        if (resetToZero) {
            rotation = 0f  // 可选：停止后恢复初始角度
        }
    }

    // 释放资源，防止内存泄漏
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopRotate()
    }
}
